package cn.yhsoft.fs;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.yhsoft.fs.gofastdfs.GoFastDFSResult;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.var;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiYong
 * 文件系统文件存储适配器
 */
public class GoFastDFSStorageAdapter implements FsStorageAdapter {
    private String serverAddress;
    private String groupName = "group1";
    private ObjectMapper objectMapper;

    public GoFastDFSStorageAdapter(String serverAddress) {
        if (!serverAddress.endsWith("/")) {
            serverAddress = serverAddress + "/";
        }
        this.serverAddress = serverAddress;
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public GoFastDFSStorageAdapter(String serverAddress, String groupName) {
        this(serverAddress);
        this.groupName = groupName;
    }

    @Override
    public String save(String path, String saveFileName, InputStream fileInputStream) {
        path = path.startsWith("/") ? path.substring(1) : path;
        path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        Map<String, Object> params = new HashMap<>();
        params.put("file", new InputStreamResource(fileInputStream, saveFileName));
        params.put("path", "/" + path);
        params.put("output", "json");
        params.put("filename", saveFileName);
        var post = HttpUtil.createPost(serverAddress + groupName + "/upload");
        post.header("Content-Type", "multipart/form-data");
        post.form(params);
        var response = post.execute();
        String resultJson = response.body();
        GoFastDFSResult result;
        try {
            result = objectMapper.readValue(resultJson, GoFastDFSResult.class);
        } catch (Exception ex) {
            throw new RuntimeException("GoFastDFS返回结构解析失败");
        }
        if (GoFastDFSResult.STATUS_FAIL.equals(result.getStatus())) {
            throw new RuntimeException(result.getMessage());
        }
        if (result.getRetcode() != 0) {
            throw new RuntimeException(result.getRetmsg());
        }
        System.out.println(result.getPath());
        return path + "/" + saveFileName;
    }

    @Override
    public InputStream getInputStream(String path) {
        var url=this.serverAddress + this.groupName + "/" + path + "?download=0";
        final HttpResponse httpResponse = HttpRequest.get(url).timeout(1000 * 2).executeAsync();
        if (httpResponse.isOk()) {
            return httpResponse.bodyStream();
        } else {
            throw new HttpException("文件服务器响应错误，状态代码: [{}]", httpResponse.getStatus());
        }
    }
}
